<template>
  <ul class="todo-main">
    <Item
      v-for="item in todoList"
      :key="item.id"
      v-bind="item"
      @getDeleteId="singleDeleteHandle"
      @getCheckedId="singleCheckedHandle"
    />
  </ul>
</template>

<script>
import Item from "./Item";
import { v4 as uuidv4 } from "uuid";
export default {
  name: "List",
  data() {
    return {
      todoList: [
        {
          id: uuidv4(),
          skill: "唱",
          done: false,
        },
        {
          id: uuidv4(),
          skill: "跳",
          done: false,
        },
        {
          id: uuidv4(),
          skill: "rap",
          done: false,
        },
      ],
    };
  },
  components: {
    Item,
  },
  methods: {
    //单个删除，子传父
    singleDeleteHandle(id) {
      this.todoList = this.todoList.filter((item) => item.id !== id);
    },
    //单选
    singleCheckedHandle(id) {
      this.todoList = this.todoList.map((item) =>
        item.id === id ? { ...item, done: !item.done } : item
      );
    },
  },
  mounted() {
    //给$bus绑定一个接受header组件传值的事件newTodo，拿到添加的数据添加到数据里
    this.$bus.$on("newTodo", (newTodo) => {
      this.todoList.unshift(newTodo);
    });
    //将todoList发布
    this.$bus.$emit("getTodoList", this.todoList);
    //将新的todoList订阅
    this.$bus.$on("newTodoList", (newTodoList) => {
      this.todoList = newTodoList;
    });
  },
  //监听todoList的状态改变视图
  watch: {
    todoList: {
      deep: true,
      handler() {
        this.$bus.$emit("getTodoList", this.todoList);
      },
    },
  },
};
</script>

<style scoped>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
</style>